/*
 * @lc app=leetcode.cn id=54 lang=golang
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
func spiralOrder(matrix [][]int) []int {
	if len(matrix) == 0 {
		return []int{}
	}

	left := 0
	right := len(matrix[0]) - 1
	top := 0
	bottom := len(matrix) - 1
	ret := []int{}
	for left < right && top < bottom {
		for i := left; i < right; i++ {
			ret = append(ret, matrix[top][i])
		}

		for i := top; i < bottom; i++ {
			ret = append(ret, matrix[i][right])
		}

		for i := right; i > left; i-- {
			ret = append(ret, matrix[bottom][i])
		}

		for i := bottom; i > top; i-- {
			ret = append(ret, matrix[i][left])
		}
	}

	if left == right {
		for i := top; i <= bottom; i++ {
			ret = append(ret, matrix[i][left])
		}
	} else if bottom == top {
		for i := left; i <= right; i++ {
			ret = append(ret, matrix[top][i])
		}
	}

	return ret
}

// @lc code=end

